package com.harmony.pilot.data.controller;

import com.harmony.pilot.common.dto.RestResult;
import com.harmony.pilot.common.dto.FunctionImplementation;
import com.harmony.pilot.data.service.FunctionImplementationService;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

/**
 * 函数实现查询控制器
 * 提供基于CodeQL的函数实现查询功能
 */
@Slf4j
@RestController
@RequestMapping("/data/function")
@RequiredArgsConstructor
public class FunctionImplementationController {
    
    private final FunctionImplementationService functionImplementationService;
    
    /**
     * 查找函数实现
     * 
     * 当用户调用其他模块的函数时，通过此接口获取函数实现，
     * 从而提供最佳的编码提示（参数类型、返回值、使用示例等）
     */
    @PostMapping("/implementation")
    public RestResult<FunctionImplementation> getFunctionImplementation(
            @RequestBody FunctionImplementationRequest request) {
        
        log.info("Finding function implementation: {} (qualified: {})", 
            request.getFunctionName(), request.getQualifiedName());
        
        FunctionImplementation impl = functionImplementationService.findFunctionImplementation(
            request.getFunctionName(),
            request.getQualifiedName(),
            request.getContextFilePath()
        );
        
        return RestResult.success(impl);
    }
    
    /**
     * 根据函数调用查找实现（智能识别）
     * 
     * 从代码上下文中识别函数调用，自动查找实现
     */
    @PostMapping("/implementation/from-context")
    public RestResult<FunctionImplementation> getFunctionImplementationFromContext(
            @RequestBody FunctionContextRequest request) {
        
        log.info("Finding function implementation from context");
        
        // 解析上下文，提取函数调用
        String functionName = extractFunctionName(request.getCode(), request.getCursorLine());
        String qualifiedName = extractQualifiedName(request.getCode(), request.getCursorLine());
        
        FunctionImplementation impl = functionImplementationService.findFunctionImplementation(
            functionName,
            qualifiedName,
            request.getFilePath()
        );
        
        return RestResult.success(impl);
    }
    
    /**
     * 从代码中提取函数名
     */
    private String extractFunctionName(String code, int cursorLine) {
        // 简单的提取逻辑：查找光标附近的函数调用
        String[] lines = code.split("\n");
        if (cursorLine >= 0 && cursorLine < lines.length) {
            String line = lines[cursorLine];
            // 匹配函数调用模式：functionName(...)
            java.util.regex.Pattern pattern = java.util.regex.Pattern.compile(
                "([a-zA-Z_][a-zA-Z0-9_]*)\\s*\\("
            );
            java.util.regex.Matcher matcher = pattern.matcher(line);
            if (matcher.find()) {
                return matcher.group(1);
            }
        }
        return null;
    }
    
    /**
     * 从代码中提取完整限定名
     */
    private String extractQualifiedName(String code, int cursorLine) {
        // 查找命名空间和类名
        String[] lines = code.split("\n");
        String namespace = null;
        String className = null;
        
        for (int i = 0; i < cursorLine && i < lines.length; i++) {
            String line = lines[i].trim();
            
            // 查找命名空间
            if (line.startsWith("namespace ")) {
                java.util.regex.Pattern nsPattern = java.util.regex.Pattern.compile(
                    "namespace\\s+([a-zA-Z_][a-zA-Z0-9_]*)"
                );
                java.util.regex.Matcher nsMatcher = nsPattern.matcher(line);
                if (nsMatcher.find()) {
                    namespace = nsMatcher.group(1);
                }
            }
            
            // 查找类名
            if (line.contains("class ")) {
                java.util.regex.Pattern classPattern = java.util.regex.Pattern.compile(
                    "class\\s+([a-zA-Z_][a-zA-Z0-9_]*)"
                );
                java.util.regex.Matcher classMatcher = classPattern.matcher(line);
                if (classMatcher.find()) {
                    className = classMatcher.group(1);
                }
            }
        }
        
        // 构建完整限定名
        if (namespace != null || className != null) {
            StringBuilder qualifiedName = new StringBuilder();
            if (namespace != null) {
                qualifiedName.append(namespace).append("::");
            }
            if (className != null) {
                qualifiedName.append(className).append("::");
            }
            return qualifiedName.toString();
        }
        
        return null;
    }
    
    @Data
    public static class FunctionImplementationRequest {
        private String functionName;
        private String qualifiedName;
        private String contextFilePath;
    }
    
    @Data
    public static class FunctionContextRequest {
        private String filePath;
        private String code;
        private int cursorLine;
        private int cursorColumn;
    }
}

